<template>
	<Content title="工单操作">
		<view class="device-details" :style="{
        'padding-bottom':
          model.state == '完成' &&
          (model.isClearLine == '是' || model.isRemoveMold == '是')
            ? '0'
            : '150rpx',
      }">
			<view class="content">
				<view class="main-box">
					<view class="info-box">
						<view class="title">
							<text class="txt u-line-1">工单号 {{ model.workCode }}</text>
							<view class="tag-box">
								<u-tag shape="circle" :text="realState" :borderColor="getColor()"
									:bgColor="getColor()"></u-tag>
							</view>
						</view>
						<view class="text-box">
							<text class="label">工序:</text>
							<text class="value">{{ model.productionProcesses }}</text>
						</view>
						<view class="text-box">
							<text class="label">产品型号:</text>
							<text class="value">{{ model.materialModel }}</text>
						</view>
						<view class="text-box">
							<text class="label">产品编号:</text>
							<text class="value">{{ model.materialCode }}</text>
						</view>
						<view class="text-box">
							<text class="label">产品名称:</text>
							<text class="value">{{ model.materialName }}</text>
						</view>
						<view class="text-box">
							<text class="label">设备编号:</text>
							<text class="value">{{ model.deviceCode }}</text>
						</view>
						<view class="text-box">
							<text class="label">模具编号:</text>
							<text class="value">{{ model.moldCode }}</text>
						</view>
						<view class="text-box">
							<text class="label">模具名称:</text>
							<text class="value">{{ model.moldName }}</text>
						</view>
						<template v-if="type == '2'">
							<view class="text-box">
								<text class="label">型腔数:</text>
								<text class="value">{{ model.cavityNum }}</text>
							</view>
							<view class="text-box">
								<text class="label">成型周期 (s):</text>
								<text class="value">{{ model.moldingCycle }}</text>
							</view>
							<view class="text-box">
								<text class="label">实际型腔数:</text>
								<text class="value">{{ model.realityCavityNum }}</text>
							</view>
							<view class="text-box">
								<text class="label">标准型腔数:</text>
								<text class="value">{{ model.standardCavities }}</text>
							</view>
						</template>
						<view class="text-box">
							<text class="label">计划数量:</text>
							<text class="value">{{ model.planProduceQuantity }}</text>
						</view>
						<view class="text-box">
							<text class="label">生产数量:</text>
							<text class="value">{{ model.produceQuantity }}</text>
						</view>
						<!-- <view class="text-box">
              <text class="label">实际成型周期(s):</text>
              <text class="value">0</text>
            </view> -->
						<view class="text-box">
							<text class="label">合格数量:</text>
							<text class="value">{{ model.qualifiedQuantity }}</text>
						</view>
						<view class="text-box">
							<text class="label">报废数量:</text>
							<text class="value">{{ model.scrapQuantity }}</text>
						</view>
						<view class="text-box">
							<text class="label">图号规格:</text>
							<text class="value">{{ model.customMaterialCode }}</text>
						</view>
						<view class="text-box">
							<text class="label">材料牌号:</text>
							<text class="value">{{ model.materialMark }}</text>
						</view>
						<view class="text-box">
							<text class="label">客户:</text>
							<text class="value">{{ model.custom }}</text>
						</view>
						<view class="text-box">
							<text class="label">备注:</text>
							<text class="value">{{ model.remarks }}</text>
						</view>
					</view>

					<view class="info-box" style="padding-bottom: 0" v-if="model.state == '转产中'">
						<view class="title">
							<text class="txt u-line-1">转产计时</text>
							<view class="tag-box"> {{ date }} </view>
						</view>
					</view>
					<u-form labelPosition="left" :model="form" labelWidth="120" labelAlign="left" :rules="rules"
						ref="uForm">
						<template v-if="model.state == '转产中'">
							<view class="info-box">
								<view class="title">
									<text class="txt u-line-1">工单信息</text>
								</view>

								<view class="text-box">
									<text class="label">转产前工单号:</text>
									<text class="value">{{ model.changeWorkCode }}</text>
								</view>
								<view class="text-box">
									<text class="label">模具编号:</text>
									<text class="value">{{ model.changeMoldCode }}</text>
								</view>
								<view class="text-box">
									<text class="label">产品编号:</text>
									<text class="value">{{ model.changeMaterialCode }}</text>
								</view>
								<view class="line"></view>
								<view class="text-box">
									<text class="label">转产后工单号:</text>
									<text class="value">{{ model.workCode }}</text>
								</view>
								<view class="text-box">
									<text class="label">模具编号:</text>
									<text class="value">{{ model.moldCode }}</text>
								</view>
								<view class="text-box">
									<text class="label">产品编号:</text>
									<text class="value">{{ model.materialCode }}</text>
								</view>
								<view class="box-item">
									<text class="label">转产类型:</text>
									<view class="value">
										<u-radio-group class="box-input" v-model="form.changingType">
											<u-radio label="换模转产" name="换模转产" style="margin-right: 10px"></u-radio>
											<u-radio label="换料转产" name="换料转产" style="margin-right: 10px"></u-radio>
											<u-radio label="产品更换转产" name="产品更换转产"></u-radio>
										</u-radio-group>
									</view>
								</view>
							</view>
							<view class="info-box">
								<view class="input-box">
									<u-form-item label="转产备注:" prop="changingRemarks">
										<u-textarea class="box-input" v-model="form.changingRemarks"
											placeholder="请输入工单信息"></u-textarea>
									</u-form-item>
								</view>
							</view>
						</template>

						<template v-if="model.state == '调机中'">
							<view class="info-box">
								<view class="title">
									<text class="txt u-line-1">调机操作</text>
								</view>

								<view class="text-box">
									<text class="label">开始调机人:</text>
									<text class="value">{{ model.ferryFlightMan }}</text>
								</view>
								<view class="text-box">
									<text class="label">开始调机时间:</text>
									<text class="value">{{ model.ferryFlightTime }}</text>
								</view>
								<view class="text-box">
									<text class="label">调机计时:</text>
									<text class="value">{{ date }}</text>
								</view>
							</view>

							<view class="info-box">
								<view class="title">
									<text class="txt u-line-1">调机备注</text>
								</view>
								<view class="input-box">
									<u-form-item label="" prop="ferryFlightRemarks">
										<u-textarea class="box-input" v-model="form.ferryFlightRemarks"
											placeholder="请输入备注信息"></u-textarea>
									</u-form-item>
								</view>
							</view>
						</template>
					</u-form>
				</view>
			</view>

			<view class="btn-v" v-if="model.state !== '完成'">
				<view class="but-box">
					<u-button class="btn" type="primary" text="开始转产" v-if="model.state == '下发'"
						@click="changeStatus('startChangeProduc')"></u-button>
					<u-button class="btn" type="primary" text="结束转产" v-if="model.state == '转产中'"
						@click="changeStatus('changeProducFinish', form)"></u-button>
					<u-button class="btn" type="primary" v-if="model.state == '转产完成'" @click="
              changeStatus('startFerryFlight', {
                ferryFlightMan: userInfo.realname,
              })
            " text="开始调机"></u-button>
					<u-button class="btn" type="primary" v-if="model.state == '调机中'"
						@click="changeStatus('ferryFlightFinish', form)" text="完成调机"></u-button>
					<u-button class="btn" type="primary" v-if="model.state == '调机完成'"
						@click="changeStatus('startProduce')" text="开始"></u-button>
					<u-button class="btn" type="primary" v-if="model.state == '生产'"
						@click="changeStatus('produceFinish')" text="完成"></u-button>
					<u-button class="btn" type="primary" v-if="model.state == '中断'"
						@click="changeStatus('restoreInterrupt')" text="恢复"></u-button>
					<u-button class="btn" type="primary" v-else-if="model.state != '下发'"
						@click="changeStatus('interrupt')" text="中断"></u-button>
				</view>
			</view>
			<view class="btn-v" v-else-if="model.isRemoveMold == '否'">
				<view class="but-box">
					<u-button class="btn" type="primary" text="拆模" @click="changeStatus('removeMold')"></u-button>
				</view>
			</view>
		</view>

		<MyModal v-model="show" title="请选择中断原因" @confirm="confirm" ref="uModal" :showCancelButton="true"
			@cancel="cancelModal">
			<view class="header" style="text-align: center; margin-bootom: 10px">
				<rich-text nodes="请选择中断原因"></rich-text>
			</view>
			<u-form :model="model1" labelWidth="80" labelAlign="left" :rules="rules1" ref="uForm1" labelPosition="top">
				<u-form-item :borderBottom="type == 'edit'" label="中断原因" prop="interruptReason" required>
					<uni-data-select v-model="model1.interruptReason" dictCode="中断原因"
						placeholder="请选择"></uni-data-select>
				</u-form-item>
			</u-form>
		</MyModal>
	</Content>
</template>

<script>
	import Content from "@/components/content/index";
	import fetch from "@/utils/fetch";
	import MyModal from "@/components/myModal";
	import {
		getUserInfo
	} from "@/store/user";
	import {
		getPageData
	} from "@/store/user";
	export default {
		components: {
			Content,
			MyModal,
		},
		data() {
			return {
				model: {
					team: "",
				},
				model1: {},
				rules1: {
					interruptReason: {
						required: true,
						message: "请输入",
						trigger: ["blur", "change"],
					},
				},
				form: {
					changingType: "换模转产",
					userName: "",
					reportType: "按数量",
				},
				show: false,
				rules: {
					scrapQuantity: {
						type: "number",
						validator: (rule, value, callback) => {
							if (!value) {
								callback();
							} else {
								if (value <= this.model.produceQuantity) {
									callback("报废数量不可大于生产数量");
								}
							}
						},
						trigger: ["blur", "change"],
					},
				},
				navIndex: 0,
				type: "1",
				date: "00:00:00",
				date1: new Date(),
				localdata: [{
						text: "按数量",
						value: "按数量",
					},
					{
						text: "按重量",
						value: "按重量",
					},
				],
				workCode: "",
				userInfo: {},
				time: "",
				realState: '',
				flag: null,
			};
		},
		onLoad: function(option) {
			//option为object类型，会序列化上个页面传递的参数
			this.workCode = option.workCode;
			this.userInfo = getUserInfo();
		},
		onReady: function() {
			this.getList();
		},
		computed: {

		},
		mounted() {

		},
		methods: {
			getStatusSwitch() {
				fetch('get', '/dms/mobile/jumpFlow', {
					workCode: this.model.workCode
				}).then(res => {
					if (res.data !== false) {
						this.$set(this.model, 'state', res.data)
						this.flag = true;
					} else {
						this.flag = null;
						this.realState = this.model.state;

					}
				})
			},
			confirm() {
				if (this.model1.interruptReason) {
					this.show = false;
					this.fun("interrupt", {
						interruptReason: this.model1.interruptReason,
					});
				} else {
					uni.$emit("openToast", {
						type: "error",
						icon: "error",
						title: "请输入中断原因!",
					});
				}
			},
			cancelModal() {
				this.show = false;
			},
			initTime() {
				const that = this;
				that.time = setInterval(() => {
					console.log("that.model.ferryFlightTime", that.model.ferryFlightTime);
					that.date = that.formatTimeDuration(
						Number(new Date()) -
						Number(
							that.model.ferryFlightTime ?
							new Date(that.model.ferryFlightTime) :
							that.date1
						)
					);
				}, 1000);
			},
			formatTimeDuration(millisecond) {
				if (millisecond < 0) {
					return "00:00:00";
				}
				let second = parseInt(millisecond / 1000);
				let minute = 0;
				let hour = 0;
				let day = 0;
				if (second > 60) {
					minute = parseInt(second / 60);
					second = parseInt(second % 60);
					if (minute > 60) {
						hour = parseInt(minute / 60);
						minute = parseInt(minute % 60);
						if (hour > 24) {
							day = parseInt(hour / 24);
							hour = parseInt(hour % 24);
						}
					}
				}
				return day > 0 ?
					`${day}天 ${hour >= 10 ? hour : "0" + hour}:${
            minute >= 10 ? minute : "0" + minute
          }:${second >= 10 ? second : "0" + second}` :
					`${hour >= 10 ? hour : "0" + hour}:${
            minute >= 10 ? minute : "0" + minute
          }:${second >= 10 ? second : "0" + second}`;
			},
			getColor() {
				const item2 = this.realState;
				return item2 == "待排产" ?
					"#E5963A" :
					item2 == "已排产" ?
					"#998BF2" :
					item2 == "下发" ?
					"#6BBEE1" :
					item2 == "生产" ?
					"#73D8A6" :
					item2 == "中断" ?
					"#D48B3E" :
					item2 == "暂停" ?
					"#D8BE49" :
					item2 == "完成" ?
					"#4668E2" :
					item2 == "转产中" ?
					"#E794C9" :
					item2 == "转产完成" ?
					"#C25BC6" :
					item2 == "调机中" ?
					"#D8B2F2" :
					item2 == "调机完成" ?
					"#8698F6" :
					item2 == "拆模" ?
					"#EA709F" :
					"#31b099";
			},
			changeStatus(val, data) {
				const that = this;
				if (val === "removeMold") {
					that.$tips("提示", "是否确认拆模？", function(res) {
						if (res.confirm) {
							that.fun(val, data);
						}
					});
					return;
				}
				if (val === "interrupt") {
					that.show = true;
					return;
				}

				// 特殊处理完成操作
				if (val === "produceFinish") {
					that.$loading.open();
					fetch("put", "/dms/mobile/" + val, null, {
						workCode: that.model.workCode,
						...data,
						flag: this.flag,
					}, true, true).then((res) => {
						that.$loading.close();

						// 如果返回code==1，显示确认对话框
						if (res.code == "1" && res.msg) {
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: true,
								cancelText: '取消',
								confirmText: '强制完成',
								success: function(modalRes) {
									if (modalRes.confirm) {
										// 用户点击强制完成，重新调用接口并传递mandatoryEnd:true
										that.$loading.open();
										fetch("put", "/dms/mobile/" + val, null, {
											workCode: that.model.workCode,
											...data,
											flag: that.flag,
											mandatoryEnd: true
										}).then((finalRes) => {
											that.$loading.close();
											if (finalRes.code === "200") {
												uni.$emit("openToast", {
													type: "success",
													title: finalRes.msg,
													complete() {
														that.form = {
															changingType: "换模转产",
															reportType: "按数量"
														};
														that.getList();
													}
												});
											} else {
												uni.$emit("openToast", {
													type: "error",
													title: finalRes.msg || "操作失败",
												});
											}
										}).catch((err) => {
											that.$loading.close();
										});
									}
								}
							});
						} else if (res.code === "200") {
							uni.$emit("openToast", {
								type: "success",
								title: res.msg,
								complete() {
									that.form = {
										changingType: "换模转产",
										reportType: "按数量"
									};
									that.getList();
								}
							});
						} else {
							uni.$emit("openToast", {
								type: "error",
								title: res.msg || "操作失败",
							});
						}
					}).catch(err => {
						that.$loading.close();
						console.log(err, 'czqError');
					});
					return;
				}

				// 其他状态直接调用fun方法
				that.fun(val, data);
			},
			fun(val, data) {
				const that = this;
				that.$loading.open();
				fetch("put", "/dms/mobile/" + val, null, {
					workCode: that.model.workCode,
					...data,
					flag: this.flag,
				}).then((res) => {
					that.$loading.close();
					uni.$emit("openToast", {
						type: "success",
						title: res.msg,
						complete() {
							that.form = {
								changingType: "换模转产",
								reportType: "按数量"
							};
							that.getList();
							if (val === "removeMold") {
								uni.navigateTo({
									url: `/pages/mold/applyRepair/index?type=add&workCode=` +
										that.model.workCode,
									animationType: "pop-in",
								});
							}
						},
					});
				}).catch(err => {
					that.$loading.close();
					console.log(err, 'czqError');
				});
			},
			getList() {
				const that = this;
				that.$loading.open();
				fetch("get", "/dms/mobile/selectWorkByWorkCode", {
					workCode: that.workCode,
				}).then(({
					data
				}) => {
					this.model = data || {};
					this.realState = this.model.state;
					if (this.time) clearInterval(this.time);
					if (this.model.state == "转产中" || this.model.state == "调机中") {
						this.date = "00:00:00";
						this.initTime();
					}
					if (this.model.state == "下发" || this.model.state == "转产完成") {
						this.getStatusSwitch();
					}
					that.$loading.close();
				});
			},
		},
		destroyed() {
			clearInterval(this.time);
			this.time = null;
		},
	};
</script>

<style scoped lang="scss">
	.device-details {
		height: 100%;
		overflow: auto;
		padding-bottom: 150rpx;

		.content {
			min-height: 100%;
		}

		.title {
			font-size: 32rpx;
			margin-bottom: 20rpx;
			padding: 0 40rpx 20rpx 40rpx;
			border-bottom: 1px solid #e0e0e0;
			display: flex;
			align-items: center;

			.txt {
				flex: 1;
			}

			.tag-box {
				display: flex;
				align-items: center;
			}
		}

		.content-top {
			padding: 40rpx;

			.state {
				color: #f17a0a;
				margin-bottom: 20rpx;
			}
		}

		.search-box {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 60rpx;

			.label {
				margin: 0 20rpx;
			}
		}
	}
</style>